/********************************************************************************
 * Copyright (c)2016-2020, ShenZhen WanJiaAn Technology CO.,LTD.
 * All Rights Reserved.
 *
 * File Name     : DevWdg.c
 * Author        : joki.zhu
 * Date          : 2020-07-06
 *
 * Record        :
 * 1.Date        : 2020-07-06
 *   Author      : joki.zhu
 *   Modification: Created file
 ********************************************************************************/
#include "app_common.h"
#include "DevSocSub.h"
#include "hi_hal_watchdog.h"

#define SOCSUB_WDG_PERIOD_TIME_SEC      (12)
#define WDG_PERIOD_TIME_SEC             (5)


/* 子芯片(mcu/wifi)看门狗   初始化 */
static int socsub_wdg_init()
{
    int ret = 0;
    char wdtState = 0;

    ret = SocSubSetWdgState(1);
    if (ret < 0) {
        LOGE("SocSubSetWdgState failed\n");
        return -1;
    }

    ret = SocSubSetWdgPeriod(SOCSUB_WDG_PERIOD_TIME_SEC * 1000);
    if (ret < 0) {
        LOGE("SocSubSetWdtPeriod failed\n");
        return -1;
    }

    return 0;
}

/* 子芯片(mcu/wifi)看门狗喂狗 */
static int socsub_wdg_feed()
{
    static char bInit = 0;
    char wdgState = 0;
    
    if (!bInit) {
        socsub_wdg_init();
        bInit = 1;
    }

    SocSubGetWdgState(&wdgState);
    if (wdgState == 1) {
        SocSubSetWdgFeed();
    }

    return 0;
}

void *tskWdg(void *args)
{
    SET_THREAD_NAME("tskWdg");
    pthread_detach(pthread_self());
    
    while (1)
    {
#ifdef SOCSUB_WDG_ENABLE
        socsub_wdg_feed();
        sleep(SOCSUB_WDG_PERIOD_TIME_SEC/2);
#else /* system wdg */
        WdgFeed();
        sleep(WDG_PERIOD_TIME_SEC/2);
#endif /* SOCSUB_WDG_ENABLE */
    }
    
    pthread_exit(0);
}

int WdgInit(void)
{
    int ret = 0;
    pthread_t wdtPid = 0;

#ifndef SOCSUB_WDG_ENABLE
    HI_HAL_WDG_Init();
#endif /* SOCSUB_WDG_ENABLE */

    ret = pthread_create(&wdtPid, 0, (void *)tskWdg, NULL);
    if (ret != 0) {
        LOGE("pthread_create tskWdg failed\n");
        return -1;
    }

    return 0;
}

int WdgFeed(void)
{
#ifndef SOCSUB_WDG_ENABLE
    HI_HAL_WDG_ClearIRQ();
#endif /* SOCSUB_WDG_ENABLE */

    return 0;
}

int WdgDeinit(void)
{
#ifndef SOCSUB_WDG_ENABLE
    HI_HAL_WDG_DeInit();
#endif /* SOCSUB_WDG_ENABLE */

    return 0;
}


